<template>
  <div class="order-create-container">
    <el-card>
      <div slot="header">
        <span>预约洗衣服务</span>
      </div>
      
      <el-form :model="orderForm" :rules="orderRules" ref="orderForm" label-width="100px">
        <el-form-item label="衣物类型" prop="clothesTypeId">
          <el-select v-model="orderForm.clothesTypeId" placeholder="请选择衣物类型" style="width: 100%">
            <el-option 
              v-for="item in clothesTypes" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="服务类型" prop="serviceTypeId">
          <el-select v-model="orderForm.serviceTypeId" placeholder="请选择服务类型" style="width: 100%" @change="handleServiceChange">
            <el-option 
              v-for="item in serviceTypes" 
              :key="item.id" 
              :label="`${item.name} (¥${item.price})`" 
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="orderForm.quantity" :min="1" @change="calculateTotal"></el-input-number>
        </el-form-item>
        
        <el-form-item label="取件地址" prop="pickupAddress">
          <el-input v-model="orderForm.pickupAddress" placeholder="请输入取件地址"></el-input>
        </el-form-item>
        
        <el-form-item label="送件地址" prop="deliveryAddress">
          <el-input v-model="orderForm.deliveryAddress" placeholder="请输入送件地址"></el-input>
        </el-form-item>
        
        <el-form-item label="取件时间" prop="pickupTime">
          <el-date-picker 
            v-model="orderForm.pickupTime" 
            type="datetime" 
            placeholder="选择取件时间"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input type="textarea" v-model="orderForm.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
        
        <el-form-item label="总金额">
          <span class="total-amount">¥{{ orderForm.totalAmount.toFixed(2) }}</span>
        </el-form-item>
        
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-radio-group v-model="orderForm.paymentMethod">
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信支付</el-radio>
            <el-radio label="cash">现金支付</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitOrder">提交订单</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getClothesTypes } from '@/api/clothesType'
import { getServiceTypes } from '@/api/serviceType'
import { createOrder } from '@/api/order'

export default {
  name: 'OrderCreate',
  data() {
    return {
      user: JSON.parse(localStorage.getItem('user') || '{}'),
      clothesTypes: [],
      serviceTypes: [],
      currentServicePrice: 0,
      orderForm: {
        userId: null,
        clothesTypeId: '',
        serviceTypeId: '',
        quantity: 1,
        pickupAddress: '',
        deliveryAddress: '',
        pickupTime: '',
        remark: '',
        totalAmount: 0,
        paymentMethod: 'alipay'
      },
      orderRules: {
        clothesTypeId: [{ required: true, message: '请选择衣物类型', trigger: 'change' }],
        serviceTypeId: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
        quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        pickupAddress: [{ required: true, message: '请输入取件地址', trigger: 'blur' }],
        deliveryAddress: [{ required: true, message: '请输入送件地址', trigger: 'blur' }],
        pickupTime: [{ required: true, message: '请选择取件时间', trigger: 'change' }],
        paymentMethod: [{ required: true, message: '请选择支付方式', trigger: 'change' }]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      }
    }
  },
  created() {
    if (!this.user || !this.user.id) {
      this.$message.error('请先登录');
      this.$router.push('/login');
      return;
    }
    
    this.orderForm.userId = this.user.id;
    
    if (this.user.address) {
      this.orderForm.pickupAddress = this.user.address;
      this.orderForm.deliveryAddress = this.user.address;
    }
    
    this.fetchClothesTypes();
    this.fetchServiceTypes();
  },
  methods: {
    async fetchClothesTypes() {
      try {
        const res = await getClothesTypes()
        if (res.code === 200) {
          this.clothesTypes = res.data
        }
      } catch (error) {
        this.$message.error('获取衣物类型失败')
      }
    },
    async fetchServiceTypes() {
      try {
        const res = await getServiceTypes()
        if (res.code === 200) {
          this.serviceTypes = res.data
        }
      } catch (error) {
        this.$message.error('获取服务类型失败')
      }
    },
    handleServiceChange(serviceTypeId) {
      const service = this.serviceTypes.find(item => item.id === serviceTypeId)
      if (service) {
        this.currentServicePrice = service.price
        this.calculateTotal()
      }
    },
    calculateTotal() {
      this.orderForm.totalAmount = this.currentServicePrice * this.orderForm.quantity
    },
    submitOrder() {
      this.$refs.orderForm.validate(async valid => {
        if (valid) {
          try {
            const res = await createOrder(this.orderForm)
            if (res.code === 200) {
              this.$message.success('订单创建成功')
              this.$router.push('/user/order/detail?orderNo=' + res.data.orderNo)
            } else {
              this.$message.error(res.message)
            }
          } catch (error) {
            this.$message.error('创建订单失败')
          }
        }
      })
    },
    resetForm() {
      this.$refs.orderForm.resetFields()
      this.orderForm.totalAmount = 0
      this.currentServicePrice = 0
    }
  }
}
</script>

<style scoped>
.order-create-container {
  padding: 20px;
}
.total-amount {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}
</style> 